package com.example.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mall.client.ProductFeignClient;
import com.example.mall.constants.BaseConstants;
import com.example.mall.domain.Order;
import com.example.mall.dto.KillPlaceOrderDto;
import com.example.mall.dto.OrderDto;
import com.example.mall.dto.PlaceOrderDto;
import com.example.mall.mapper.OrderDetailsMapper;
import com.example.mall.mapper.OrderMapper;
import com.example.mall.query.OrderQuery;
import com.example.mall.query.PageDTO;
import com.example.mall.result.JSONResult;
import com.example.mall.service.IOrderService;
import com.example.mall.to.KilledInfo;
import com.example.mall.util.AssertUtil;
import com.example.mall.util.CodeGenerateUtils;
import com.example.mall.util.CopyUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单主表 服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-05-09
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 异步下单，处理高并发
     * 同一个课程可以多次下单，但是不能冲突提交表单
     */
    @Override
    public JSONResult placeOrder(PlaceOrderDto dto) {
        return placeAnOrder(dto,null);
    }

    @Override
    public JSONResult killPlaceOrder(KillPlaceOrderDto dto) {
        return null;
    }

    @Override
    public Object selectByOrderNo(String orderNo) {
        return null;
    }

    private JSONResult placeAnOrder(PlaceOrderDto dto, KilledInfo killedInfo) {
        //校验参数
        AssertUtil.isNotNull(dto.getProductIds(),"无效的商品ID");
        //秒杀下单的话，只能有1个商品
        if(killedInfo != null){
            AssertUtil.isTrue(dto.getProductIds().size() == 1,"非法请求[秒杀课程只能有1种]");
        }
        AssertUtil.isNotEmpty(dto.getToken(),"非法请求");
        //Token判断重复提交
        boolean hasKey = redisTemplate.hasKey(dto.getToken());
        AssertUtil.isTrue(hasKey,"表单重复提交，请重新发起下单请求");
        return null;
    }

    @Override
    public PageDTO<OrderDto> queryPage(OrderQuery orderQuery) {
        if (orderQuery == null) {
            orderQuery = new OrderQuery();
        }
        Page<Order> page = orderQuery.toMpPageByDefaultCreateTimeAsc();
        Page<Order> cartPage = lambdaQuery()
                .like(orderQuery.getOrderId()!= null, Order::getOrderId, orderQuery.getOrderId())
                .like(orderQuery.getUserId()!= null, Order::getUserId, orderQuery.getUserId())
                .like(orderQuery.getOrderStatus()!= null, Order::getOrderStatus, orderQuery.getOrderStatus())
                .like(orderQuery.getTotalAmount()!= null, Order::getTotalAmount, orderQuery.getTotalAmount())
                .like(orderQuery.getDiscountAmount()!= null, Order::getDiscountAmount, orderQuery.getDiscountAmount())
                .like(orderQuery.getFinalAmount()!= null, Order::getFinalAmount, orderQuery.getFinalAmount())
                .like(orderQuery.getPaymentMethod()!= null, Order::getPaymentMethod, orderQuery.getPaymentMethod())
                .like(orderQuery.getPaymentStatus()!= null, Order::getPaymentStatus, orderQuery.getPaymentStatus())
                .like(orderQuery.getOrderNo()!= null, Order::getOrderNo, orderQuery.getOrderNo())
                .like(orderQuery.getTitle()!= null, Order::getTitle, orderQuery.getTitle())
                .orderByDesc(Order::getUpdateDate)
                .page(page);
        return PageDTO.of(cartPage, OrderDto.class);
    }

    @Override
    public Order queryOrderById(Long orderId) {
        AssertUtil.isNotNull(orderId,"订单ID不能为空");
        return orderMapper.selectById(orderId);
    }

    @Override
    public List<Order> queryOrderList() {
        return this.list();
    }

    @Override
    public void update(OrderDto orderDto) {
        AssertUtil.isNotNull(orderDto.getOrderId(),"订单ID不能为空");
        Order order = this.queryOrderById(orderDto.getOrderId());
        AssertUtil.isNotNull(order,"订单不存在");
        CopyUtils.copyProperties(orderDto,order);
        order.setUpdateDate(new Date());
        orderMapper.updateById(order);
    }

    @Override
    public void delete(Long orderId) {
        AssertUtil.isNotNull(orderId,"订单ID不能为空");
        Order order = orderMapper.selectById(orderId);
        AssertUtil.isNotNull(order,"订单不存在");
        order.setUpdateDate(new Date());
        order.setPaymentStatus(BaseConstants.CANCEL);
        orderMapper.updateById(order);
    }

    @Override
    public void deleteBatch(List<Long> orderIds) {
        AssertUtil.isNotNull(orderIds,"订单ID列表不能为空");
        List<Order> order = orderMapper.selectBatchIds(orderIds);
        AssertUtil.isNotNull(order,"订单不存在");
        order.forEach(o -> {
            o.setUpdateDate(new Date());
            o.setPaymentStatus(BaseConstants.CANCEL);
            orderMapper.updateById(o);
        });
    }

    @Override
    public void insert(OrderDto orderDto) {
        Order order = new Order();
        CopyUtils.copyProperties(orderDto,order);
        order.setOrderId(CodeGenerateUtils.generateUniqueId());
        order.setCreateDate(new Date());
        order.setUpdateDate(new Date());
        order.setOrderStatus(BaseConstants.OrderStatus.STATUS_WAIT_PAY);
        order.setPaymentStatus(BaseConstants.CANCEL);
        orderMapper.insert(order);
    }
}
